package com.eastfair.venueservice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.auth.api.AuthServiceFeign;
import com.eastfair.auth.vo.OrganizationVo;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.base.entity.SuperEntity;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.projectcore.enumeration.DataIsolationSystemSceneEnum;
import com.eastfair.venueservice.dao.ServicePriceListItemMapper;
import com.eastfair.venueservice.dto.*;
import com.eastfair.venueservice.entity.*;
import com.eastfair.venueservice.enumeration.ServiceItemServiceStateEnum;
import com.eastfair.venueservice.service.*;
import com.eastfair.venueservice.vo.ServicePriceListDetailVO;
import com.eastfair.venueservice.vo.ServicePriceListItemVO;
import com.eastfair.venueservice.vo.ServicePriceListVO;
import com.eastfair.venueservice.vo.ServiceProviderVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 服务价目信息表
 * </p>
 *
 * @author linan
 * @date 2022-07-21
 */
@Slf4j
@Service
public class ServicePriceListItemServiceImpl extends SuperServiceImpl<ServicePriceListItemMapper, ServicePriceListItem> implements ServicePriceListItemService {


    public static final String[] COLUMNS = {"id", "createBy", "createTime", "updateTime", "updateBy"};
    @Resource
    private ServiceItemDetailService serviceItemDetailService;
    @Resource
    private ServiceItemService serviceItemService;
    @Resource
    private ServicePriceListDetailService servicePriceListDetailService;
    @Resource
    private ServiceCategoryService serviceCategoryService;
    @Resource
    private ServiceSpecsService serviceSpecsService;
    @Resource
    private ServiceInventoryService serviceInventoryService;
    @Resource
    private ServiceProviderService serviceProviderService;
    @Resource
    private AuthServiceFeign authServiceFeign;
    @Resource
    private ExhibitionManageService exhibitionManageService;
    @Resource
    private ServicePriceListService servicePriceListService;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<ServicePriceListItem> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }

    @Override
    protected R<Boolean> handlerSave(ServicePriceListItem model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        model.setTenantId(ContextUtil.getTenantId());
        return R.successDef();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addPriceListItems(ServicePriceListDTO servicePriceList) {
        Long priceListId = servicePriceList.getId();
        // 没任何提交则直接返回
        List<ServicePriceListItemDTO> servicePriceListItems = servicePriceList.getServicePriceListItems();
        if (CollectionUtils.isEmpty(servicePriceListItems)) {
            // 更新价目下服务数量
            updateServiceNum(priceListId);
            return true;
        }
        // 要插入的价目服务
        for (ServicePriceListItemDTO serviceItem : servicePriceListItems) {
            ServicePriceListItem servicePriceListItem = BeanUtil.copyProperties(serviceItem,ServicePriceListItem.class,"id");
            servicePriceListItem.setPriceListId(servicePriceList.getId());
            save(servicePriceListItem);
            // 要插入的服务规格详情
            if(CollectionUtils.isNotEmpty(serviceItem.getServicePriceListDetailList())){
                List<ServicePriceListDetailDTO> servicePriceListDetailList = serviceItem.getServicePriceListDetailList();
                for (ServicePriceListDetailDTO servicePriceListDetailDTO : servicePriceListDetailList) {
                    ServicePriceListDetail servicePriceListDetail = BeanUtil.copyProperties(servicePriceListDetailDTO, ServicePriceListDetail.class, "id");
                    // 价目服务表id
                    servicePriceListDetail.setServicePriceId(servicePriceListItem.getId());
                    servicePriceListDetailService.save(servicePriceListDetail);
                }
            }
        }
        // 更新价目下服务数量
        updateServiceNum(priceListId);
        return true;
    }

    /**
     * 更新价目下服务数量
     * @param priceListId priceListId
     */
    private void updateServiceNum(Long priceListId) {
        int count = count(new QueryWrapper<ServicePriceListItem>().lambda().eq(ServicePriceListItem::getPriceListId, priceListId).eq(ServicePriceListItem::getIsDeleted, BusinessConstant.NO));
        servicePriceListService.updateById(ServicePriceList.builder().id(priceListId).serviceNum(count).build());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateAllPriceListItem(ServicePriceListDTO servicePriceListDTO) {
        if(Objects.nonNull(servicePriceListDTO.getIsForHome())
                || Objects.nonNull(servicePriceListDTO.getIsForSponsor())
                || Objects.nonNull(servicePriceListDTO.getIsForTransport()) ){
            LambdaUpdateWrapper<ServicePriceListItem> set = new UpdateWrapper<ServicePriceListItem>().lambda().eq(ServicePriceListItem::getIsDeleted, BusinessConstant.NO).eq(ServicePriceListItem::getPriceListId, servicePriceListDTO.getId())
                    .set(Objects.nonNull(servicePriceListDTO.getIsForHome()), ServicePriceListItem::getIsForHome, servicePriceListDTO.getIsForHome())
                    .set(Objects.nonNull(servicePriceListDTO.getIsForSponsor()), ServicePriceListItem::getIsForSponsor, servicePriceListDTO.getIsForSponsor())
                    .set(Objects.nonNull(servicePriceListDTO.getIsForTransport()), ServicePriceListItem::getIsForTransport, servicePriceListDTO.getIsForTransport());
            return update(set);
        }
        return true;
    }

    @Override
    public R<IPage<ServicePriceListItemVO>> queryPriceListItem(PageParams<ServicePriceListItemQuery> servicePriceListItem) {
        Page<ServicePriceListItem> buildPage = servicePriceListItem.buildPage();
        Page<ServicePriceListItemVO> result = servicePriceListItem.buildPage();

        ServicePriceListItemQuery model = servicePriceListItem.getModel();
        List<Long> serviceItemIds = new ArrayList<>(8);
        // 处理服务id
        dealServiceItemIds(model, serviceItemIds);
        QueryWrapper<ServicePriceListItem> queryWrapper = new QueryWrapper<>();
        packageWrapper(model, serviceItemIds, queryWrapper);
        buildPage = page(buildPage, queryWrapper);
        BeanUtil.copyProperties(buildPage, result);
        List<ServicePriceListItem> records = buildPage.getRecords();
        // 获取所有服务ID
        serviceItemIds = records.stream().map(ServicePriceListItem::getServiceItemId).collect(Collectors.toList());
        List<Long> servicePriceIds = records.stream().map(ServicePriceListItem::getId).collect(Collectors.toList());
        List<ServiceItem> serviceItems = CollectionUtils.isNotEmpty(serviceItemIds) ? serviceItemService.listByIds(serviceItemIds) : Collections.emptyList();
        Map<Long, ServiceItem> serviceItemMap = serviceItems.stream().collect(Collectors.toMap(ServiceItem::getId, Function.identity()));
        // 查询所有服务分类和分类规格
        List<Long> serviceCategoryIds = serviceItems.stream().map(ServiceItem::getServiceCategoryId).collect(Collectors.toList());
        List<ServiceCategory> serviceCategories =CollectionUtils.isNotEmpty(serviceCategoryIds) ? serviceCategoryService.listByIds(serviceCategoryIds): Collections.emptyList();
        Map<Long, String> serviceCategoryMap = serviceCategories.stream().collect(Collectors.toMap(ServiceCategory::getId, ServiceCategory::getServiceCategoryName));
        List<ServiceSpecs> serviceSpecsList = CollectionUtils.isNotEmpty(serviceCategoryIds) ?serviceSpecsService.list(new QueryWrapper<ServiceSpecs>().lambda()
                .in(ServiceSpecs::getServiceCategoryId, serviceCategoryIds)
                .eq(ServiceSpecs::getIsDeleted, BusinessConstant.NO)): Collections.emptyList();
        Map<Long, String> serviceSpecsMap = serviceSpecsList.stream().collect(Collectors.toMap(ServiceSpecs::getId, ServiceSpecs::getServiceSpecsName));

        // 查询服务规格明细
        List<ServiceItemDetail> serviceItemDetails = CollectionUtils.isNotEmpty(serviceItemIds) ? serviceItemDetailService.list(new QueryWrapper<ServiceItemDetail>().lambda()
                .in(ServiceItemDetail::getServiceItemId, serviceItemIds)
                .eq(ServiceItemDetail::getIsDeleted, BusinessConstant.NO)) : Collections.emptyList();
        Map<Long, ServiceItemDetail> serviceItemDetailsMap = serviceItemDetails.stream().collect(Collectors.toMap(ServiceItemDetail::getId, Function.identity()));
        // 查询所有价目服务规格明细
        List<ServicePriceListDetail> servicePriceListDetails = CollectionUtils.isNotEmpty(servicePriceIds) ? servicePriceListDetailService.list(new QueryWrapper<ServicePriceListDetail>().lambda()
                .in(ServicePriceListDetail::getServicePriceId, servicePriceIds)
                .eq(ServicePriceListDetail::getIsDeleted, BusinessConstant.NO)): Collections.emptyList();
        // 查询所有服务库存
        List<ServiceInventory> serviceInventories = CollectionUtils.isNotEmpty(serviceItemIds) ? serviceInventoryService.list(new QueryWrapper<ServiceInventory>().lambda().in(ServiceInventory::getServiceItemId, serviceItemIds).eq(ServiceInventory::getIsDeleted, BusinessConstant.NO)) : Collections.emptyList();
        Map<String, ServiceInventory> serviceInventoryMap = serviceInventories.stream().collect(Collectors.toMap(e -> e.getServiceItemId() + "_" + e.getServiceCategoryId() + "_" + e.getServiceSpecsId(), Function.identity()));
        Map<Long, List<ServicePriceListDetailVO>> servicePriceListDetailMap = getInventoryMap(serviceCategoryMap, serviceSpecsMap, serviceItemDetailsMap, servicePriceListDetails, serviceInventoryMap);
        // 服务部门、服务商名称 （id全局唯一）
        List<Long> serviceProviderIds = serviceItems.stream().map(ServiceItem::getServiceProviderId).collect(Collectors.toList());
        Map<Long, String> names = new HashMap<>(8);
        names = packageOrgNames(serviceProviderIds, names);
        List<ServicePriceListItemVO> servicePriceListItemVos = new ArrayList<>();
        // 遍历处理VO
        forDealVO(records, serviceItemMap, serviceCategoryMap, servicePriceListDetailMap, names, servicePriceListItemVos);
        result.setRecords(servicePriceListItemVos);
        return R.success(result);
    }

    /**
     * 拼装机构名称
     * @param serviceProviderIds serviceProviderIds
     * @param names names
     * @return Map<Long, String>
     */
    private Map<Long, String> packageOrgNames(List<Long> serviceProviderIds, Map<Long, String> names) {
        if (CollectionUtils.isNotEmpty(serviceProviderIds)) {
            // 服务商名称
            names = serviceProviderService.listServiceProviderByIds(serviceProviderIds).stream().collect(Collectors.toMap(ServiceProviderVO::getId, ServiceProviderVO::getCompanyName));
            // 部门名称
            List<OrganizationVo> data = authServiceFeign.queryList(serviceProviderIds).getData();
            if (CollectionUtils.isNotEmpty(data)) {
                names.putAll(data.stream().collect(Collectors.toMap(OrganizationVo::getId, OrganizationVo::getName)));
            }
        }
        return names;
    }

    /**
     * 拼装wrapper
     * @param model model
     * @param serviceItemIds serviceItemIds
     * @param queryWrapper queryWrapper
     */
    private void packageWrapper(ServicePriceListItemQuery model, List<Long> serviceItemIds, QueryWrapper<ServicePriceListItem> queryWrapper) {
        queryWrapper.lambda()
                .eq(ServicePriceListItem::getIsDeleted, BusinessConstant.NO)
                .eq(Objects.nonNull(model.getId()), ServicePriceListItem::getId, model.getId())
                .eq(Objects.nonNull(model.getPriceListId()), ServicePriceListItem::getPriceListId, model.getPriceListId())
                .eq(DataIsolationSystemSceneEnum.P_COMPOSITE_COURT.eq(model.getSystemScene()), ServicePriceListItem::getIsForHome, BusinessConstant.YES)
                // TODO: 2022/7/23   .eq(DataIsolationSystemSceneEnum.P_COMPOSITE_COURT.eq(model.getSystemScene()),ServicePriceListItem::getIsForSponsor, BusinessConstant.YES)
                .eq(DataIsolationSystemSceneEnum.P_COMPOSITE_TRANSPORT.eq(model.getSystemScene()), ServicePriceListItem::getIsForTransport, BusinessConstant.YES)
                .in(StringUtils.isNotBlank(model.getServiceItemName()), ServicePriceListItem::getServiceItemId, serviceItemIds)
                .orderByDesc(ServicePriceListItem::getCreateTime);
    }

    @Override
    public R<ServicePriceListVO> queryPriceListByExhibition(ServicePriceListQuery query) {
        // 查询展会
        Long exhibitionManageId = query.getExhibitionManageId();
        ExhibitionManage exhibitionManage = exhibitionManageService.getById(exhibitionManageId);
        // 没查到展会返回null
        if (Objects.isNull(exhibitionManage) || Objects.isNull(exhibitionManage.getPriceListId())) {
            log.warn("未查找到对应展会 {}",query.getExhibitionManageId());
            return R.success(null);
        }
        Long priceListId = exhibitionManage.getPriceListId();
        // 查询价目服务
        ServicePriceList servicePriceList = servicePriceListService.getById(priceListId);
        ServicePriceListVO servicePriceListVO = BeanUtil.copyProperties(servicePriceList, ServicePriceListVO.class);
        if(Objects.isNull(servicePriceList)){
            log.warn("未查找到对应价目 {}",priceListId);
            return R.success(null);
        }
        PageParams<ServicePriceListItemQuery> pageParams = new PageParams<>();
        pageParams.setCurrent(0L);
        pageParams.setSize(99999999L);
        ServicePriceListItemQuery servicePriceListItemQuery = new ServicePriceListItemQuery();
        servicePriceListItemQuery.setPriceListId(priceListId);
        servicePriceListItemQuery.setSystemScene(query.getSystemScene());
        pageParams.setModel(servicePriceListItemQuery);
        List<ServicePriceListItemVO> records = queryPriceListItem(pageParams).getData().getRecords();
        servicePriceListVO.setServicePriceListItem(records);
        return R.success(servicePriceListVO);
    }

    @Override
    public List<ServicePriceListItem> listByExhibitionManageId(Long exhibitionManageId) {
        // 查询展会
        ExhibitionManage exhibitionManage = exhibitionManageService.getById(exhibitionManageId);
        if (exhibitionManage == null) {
            return Collections.emptyList();
        }
        Long priceListId = exhibitionManage.getPriceListId();
        if (priceListId == null) {
            return Collections.emptyList();
        }
        QueryWrapper<ServicePriceListItem> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(ServicePriceListItem::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(ServicePriceListItem::getPriceListId, priceListId);
        ;
        return list(queryWrapper);
    }

    @Override
    public void removeByServiceItemId(Long serviceItemId) {
        List<ServicePriceListItem> list = list(new QueryWrapper<ServicePriceListItem>().lambda().eq(ServicePriceListItem::getServiceItemId, serviceItemId).eq(ServicePriceListItem::getIsDeleted, BusinessConstant.NO));
        if(CollectionUtils.isNotEmpty(list)){
            // 查一个价目id
            ServicePriceListItem priceListItem = list.get(0);
            this.removeByIdsOfLogic(list);
            List<Long> itemIds = list.stream().map(SuperEntity::getId).collect(Collectors.toList());
            servicePriceListDetailService.update(new UpdateWrapper<ServicePriceListDetail>().lambda().in(ServicePriceListDetail::getServicePriceId, itemIds).set(ServicePriceListDetail::getIsDeleted,BusinessConstant.NO));
            updateServiceNum(priceListItem.getPriceListId());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updatePriceListItem(List<ServicePriceListItemDTO> servicePriceListItems) {
        // 查询所有的价目

        boolean b = false;
        for (ServicePriceListItemDTO servicePriceListItem : servicePriceListItems) {
            ServicePriceListItem item = BeanUtil.copyProperties(servicePriceListItem, ServicePriceListItem.class);
            if (Objects.nonNull(item.getIsForHome()) || Objects.nonNull(item.getIsForTransport()) || Objects.nonNull(item.getIsForSponsor())) {
                b = updateById(item);
                // 允许绑定展会后，修改开放权限
                // todo 主办待定
                // 处理主场服务
                if(item.getIsForHome().equals(BusinessConstant.YES)){

                }

            }
        }
        return b;
    }

    @Override
    public Boolean delPriceListItemBatch(List<ServicePriceListItemDTO> servicePriceListItems) {
        // 查一个价目id
        ServicePriceListItem priceListItem = getById(servicePriceListItems.get(0).getId());
        // 删除主场、主运服务
        List<ServicePriceListItem> servicePriceListItemList = this.listByIds(servicePriceListItems.stream().map(ServicePriceListItemDTO::getId).collect(Collectors.toList()));
        delServiceItem(servicePriceListItemList);
        boolean b = removeByIdsOfLogic(ConvertUtil.convertList(servicePriceListItems, ServicePriceListItem.class));
        // 更新价目服务数量
        if(Objects.nonNull(priceListItem)){
            updateServiceNum(priceListItem.getPriceListId());
        }
        return b;
    }

    @Override
    public void delByServicePriceList(ServicePriceListDTO servicePriceList) {
        List<ServicePriceListItem> list = list(new QueryWrapper<ServicePriceListItem>().lambda().in(ServicePriceListItem::getPriceListId, servicePriceList.getId())
                .eq(ServicePriceListItem::getIsDeleted, BusinessConstant.NO));
        delServiceItem(list);
    }

    @Override
    public R<ServicePriceListVO> queryPriceListById(ServicePriceListQuery query) {
        // 查询价目
        ServicePriceList priceList = servicePriceListService.getById(query.getId());
        // 没查到价目返回null
        if (Objects.isNull(priceList)) {
            log.warn("未查找到对应价目 {}",query.getId());
            return R.success(null);
        }
        ServicePriceListVO servicePriceListVO = BeanUtil.copyProperties(priceList, ServicePriceListVO.class);
        PageParams<ServicePriceListItemQuery> pageParams = new PageParams<>();
        pageParams.setCurrent(0L);
        pageParams.setSize(99999999L);
        ServicePriceListItemQuery servicePriceListItemQuery = new ServicePriceListItemQuery();
        servicePriceListItemQuery.setPriceListId(priceList.getId());
        servicePriceListItemQuery.setSystemScene(query.getSystemScene());
        pageParams.setModel(servicePriceListItemQuery);
        List<ServicePriceListItemVO> records = queryPriceListItem(pageParams).getData().getRecords();
        servicePriceListVO.setServicePriceListItem(records);
        // 查询是否绑定了展会
        ExhibitionManage exhibitionManage = exhibitionManageService.getOne(new QueryWrapper<ExhibitionManage>().lambda().eq(ExhibitionManage::getPriceListId, query.getId()).eq(ExhibitionManage::getIsDeleted, BusinessConstant.NO));
        if(Objects.nonNull(exhibitionManage)){
            servicePriceListVO.setExhibitionManageId(exhibitionManage.getId());
        }
        return R.success(servicePriceListVO);
    }

    @Override
    public R<Boolean> saveAllPriceList(ServicePriceListDTO dto) {
        // 历史记录
        R<ServicePriceListVO> priceListVOR = queryPriceListById(ServicePriceListQuery.builder().id(dto.getId()).build());
        // 先软删价目服务
        update(new UpdateWrapper<ServicePriceListItem>().lambda().eq(ServicePriceListItem::getPriceListId, dto.getId())
                .eq(ServicePriceListItem::getIsDeleted, BusinessConstant.NO).set(ServicePriceListItem::getIsDeleted, BusinessConstant.YES));
        Boolean aBoolean = addPriceListItems(dto);
        // 查询价目是否绑定了展会
        ExhibitionManage exhibitionManage = exhibitionManageService.getOne(new QueryWrapper<ExhibitionManage>().lambda().eq(ExhibitionManage::getPriceListId, dto.getId()).eq(ExhibitionManage::getIsDeleted, BusinessConstant.NO));
        if(Objects.nonNull(exhibitionManage)){
            ServicePriceListVO data = priceListVOR.getData();
            List<ServicePriceListItemVO> servicePriceListItem = data.getServicePriceListItem();
            Map<Long, ServicePriceListItemVO> priceListItemVOMap = servicePriceListItem.stream().collect(Collectors.toMap(ServicePriceListItemVO::getServiceItemId, Function.identity()));
            List<ServicePriceListItemDTO> servicePriceListItems = dto.getServicePriceListItems();
            // 下游需要修改为unable的服务
            List<ServicePriceListItemVO> needDownHomeList = new ArrayList<>();
            List<ServicePriceListItemVO> needDownTransportList = new ArrayList<>();
            // 下游需要修改为enable的服务
            List<ServicePriceListItemDTO> needAddHomeList = new ArrayList<>();
            List<ServicePriceListItemDTO> needAddTransportList = new ArrayList<>();
            for (ServicePriceListItemDTO priceListItem : servicePriceListItems) {
                // 匹配历史数据
                ServicePriceListItemVO servicePriceListItemVO = priceListItemVOMap.get(priceListItem.getServiceItemId());
                if(Objects.nonNull(servicePriceListItemVO)){
                    // 判断是否发生了变化
                    // 是否对主场开放
                    if(!priceListItem.getIsForHome().equals(servicePriceListItemVO.getIsForHome())){
                        if(BusinessConstant.NO == priceListItem.getIsForHome()){
                            //需要下架下游
                            needDownHomeList.add(servicePriceListItemVO);
                        }
                    }
                    if(!priceListItem.getIsForTransport().equals(servicePriceListItemVO.getIsForTransport())){
                        if(BusinessConstant.NO == priceListItem.getIsForHome()){
                            //需要下架下游
                            needDownTransportList.add(servicePriceListItemVO);
                        }
                    }
                    // todo 是否对主办开放
                    priceListItemVOMap.remove(priceListItem.getServiceItemId());
                }else {
                    // 未找到记录，需要同步服务
                    if(BusinessConstant.YES == priceListItem.getIsForHome()){
                        needAddHomeList.add(priceListItem);
                    }
                    if(BusinessConstant.YES == priceListItem.getIsForHome()){
                        //需要下架下游
                        needAddTransportList.add(priceListItem);
                    }
                }
            }
            // 下游需要删除的服务
            List<ServicePriceListItemVO> needDelList = new ArrayList<>(priceListItemVOMap.values());
            // 删除下游服务
            List<Long> delSourceIds = needDelList.stream().map(ServicePriceListItemVO::getId).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(delSourceIds)){
                serviceItemService.update(new UpdateWrapper<ServiceItem>().lambda().in(ServiceItem::getSourceId, delSourceIds)
                        .eq(ServiceItem::getIsDeleted,BusinessConstant.NO).set(ServiceItem::getIsDeleted,BusinessConstant.YES));
            }
            // unable下游服务 20220809 改成直接删下游
            List<Long> needDownHomeIds = needDownHomeList.stream().map(ServicePriceListItemVO::getServiceItemId).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(needDownHomeIds)){
                serviceItemService.update(new UpdateWrapper<ServiceItem>().lambda().in(ServiceItem::getSourceId, needDownHomeIds)
                        .eq(ServiceItem::getIsDeleted,BusinessConstant.NO)
                        .eq(ServiceItem::getServiceProviderType,DataIsolationSystemSceneEnum.P_COMPOSITE_COURT.getCode())
                        .eq(ServiceItem::getSourceProvider,DataIsolationSystemSceneEnum.P_COMPOSITE_VENUE.getCode())
                        .set(ServiceItem::getIsDeleted,BusinessConstant.YES));
            }
            List<Long> needDownTransportIds = needDownTransportList.stream().map(ServicePriceListItemVO::getServiceItemId).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(needDownTransportIds)){
                serviceItemService.update(new UpdateWrapper<ServiceItem>().lambda().in(ServiceItem::getSourceId, needDownTransportIds)
                        .eq(ServiceItem::getIsDeleted,BusinessConstant.NO)
                        .eq(ServiceItem::getServiceProviderType,DataIsolationSystemSceneEnum.P_COMPOSITE_TRANSPORT.getCode())
                        .eq(ServiceItem::getSourceProvider,DataIsolationSystemSceneEnum.P_COMPOSITE_VENUE.getCode())
                        .set(ServiceItem::getIsDeleted,BusinessConstant.YES));
            }
        }
        // todo 发送主场站内信
        return R.success(aBoolean);
    }

    /**
     * 删除价目下服务的下游服务
     * @param list list
     */
    private void delServiceItem(List<ServicePriceListItem> list) {
        List<Long> serviceItemIds = list.stream().map(ServicePriceListItem::getServiceItemId).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(serviceItemIds)){
            // 查询是否存在下游服务
            List<ServiceItem> afterServiceItems = serviceItemService.list(new QueryWrapper<ServiceItem>().lambda()
                    .in(ServiceItem::getSourceId,serviceItemIds)
                    .eq(ServiceItem::getIsDeleted, BusinessConstant.NO));
            for (ServiceItem afterServiceItem : afterServiceItems) {
                if (Objects.nonNull(afterServiceItem)) {
                    ServiceItemDTO copyServiceItemDTO = new ServiceItemDTO();
                    copyServiceItemDTO.setId(afterServiceItem.getId());
                    // 循环处理
                    serviceItemService.delServiceItem(copyServiceItemDTO,true);
                }
            }
        }
    }

    /**
     * 查询所有服务库存
     * @param serviceCategoryMap serviceCategoryMap
     * @param serviceSpecsMap serviceSpecsMap
     * @param serviceItemDetailsMap serviceItemDetailsMap
     * @param servicePriceListDetails servicePriceListDetails
     * @param serviceInventoryMap serviceInventoryMap
     * @return
     */
    private Map<Long, List<ServicePriceListDetailVO>> getInventoryMap(Map<Long, String> serviceCategoryMap, Map<Long, String> serviceSpecsMap, Map<Long, ServiceItemDetail> serviceItemDetailsMap, List<ServicePriceListDetail> servicePriceListDetails, Map<String, ServiceInventory> serviceInventoryMap) {
        return servicePriceListDetails.stream().map(e -> {
            ServicePriceListDetailVO servicePriceListDetailVO = BeanUtil.copyProperties(e, ServicePriceListDetailVO.class);
            // 服务规格明细表id
            Long serviceItemDetailId = e.getServiceItemDetailId();
            ServiceItemDetail serviceItemDetail = serviceItemDetailsMap.get(serviceItemDetailId);

            if (Objects.nonNull(serviceItemDetail)) {
                ServiceInventory serviceInventory = serviceInventoryMap.get(serviceItemDetail.getServiceItemId() + "_" + serviceItemDetail.getServiceCategoryId() + "_" + serviceItemDetail.getServiceSpecsId());
                if (Objects.nonNull(serviceInventory)) {
                    // 库存编码
                    servicePriceListDetailVO.setInventoryCode(serviceInventory.getInventoryCode());
                    servicePriceListDetailVO.setEarlyWarningValue( serviceInventory.getEarlyWarningValue());
                    servicePriceListDetailVO.setInventoryNum(serviceInventory.getInventoryNum());
                }
                servicePriceListDetailVO.setServiceCategoryName(serviceCategoryMap.get(serviceItemDetail.getServiceCategoryId()));
                servicePriceListDetailVO.setServiceCategoryId(serviceItemDetail.getServiceCategoryId());
                servicePriceListDetailVO.setServiceSpecsName(serviceSpecsMap.get(serviceItemDetail.getServiceSpecsId()));
                servicePriceListDetailVO.setServiceSpecsId(serviceItemDetail.getServiceSpecsId());
            }
            return servicePriceListDetailVO;
        }).collect(Collectors.groupingBy(ServicePriceListDetailVO::getServicePriceId));
    }

    /**
     * 遍历处理VO
     * @param records records
     * @param serviceItemMap serviceItemMap
     * @param serviceCategoryMap serviceCategoryMap
     * @param servicePriceListDetailMap servicePriceListDetailMap
     * @param names names
     * @param servicePriceListItemVOS servicePriceListItemVOS
     */
    private void forDealVO(List<ServicePriceListItem> records, Map<Long, ServiceItem> serviceItemMap, Map<Long, String> serviceCategoryMap, Map<Long, List<ServicePriceListDetailVO>> servicePriceListDetailMap, Map<Long, String> names, List<ServicePriceListItemVO> servicePriceListItemVOS) {
        for (ServicePriceListItem record : records) {
            ServicePriceListItemVO servicePriceListItemVO = BeanUtil.copyProperties(record, ServicePriceListItemVO.class);

            ServiceItem serviceItem = serviceItemMap.get(record.getServiceItemId());
            if (Objects.nonNull(serviceItem)) {
                // 图片Url
                servicePriceListItemVO.setPicUrl(serviceItem.getPicUrl());
                // 服务名称
                servicePriceListItemVO.setServiceItemName(serviceItem.getServiceName());
                // 服务分类
                servicePriceListItemVO.setServiceCategoryName(serviceCategoryMap.get(serviceItem.getServiceCategoryId()));
                // 计量单位
                servicePriceListItemVO.setCalUnit(serviceItem.getCalUnit());
                // 最小预定量
                servicePriceListItemVO.setMinAllocatedNum(serviceItem.getMinAllocatedNum());
                // 服务部门/服务商
                servicePriceListItemVO.setServiceProviderName(names.get(serviceItem.getServiceProviderId()));
                // 规格明细
                servicePriceListItemVO.setServicePriceListDetailList(servicePriceListDetailMap.get(servicePriceListItemVO.getId()));
                servicePriceListItemVOS.add(servicePriceListItemVO);
            }
        }
    }

    /**
     * 查询关键词下所有服务id
     * @param model
     * @param serviceItemIds
     */
    private void dealServiceItemIds(ServicePriceListItemQuery model, List<Long> serviceItemIds) {
        if (StringUtils.isNotBlank(model.getServiceItemName())) {
            // 查询关键词下所有服务
            LambdaQueryWrapper<ServiceItem> exists = new QueryWrapper<ServiceItem>().lambda()
                    .eq(ServiceItem::getIsDeleted, BusinessConstant.NO)
                    .like(ServiceItem::getServiceName, model.getServiceItemName())
                    .exists("select 1 from vsm_service_price_list_item where vsm_service_item.id=vsm_service_price_list_item.service_item_id and vsm_service_price_list_item.is_deleted=0");
            serviceItemIds = serviceItemService.list(exists).stream().map(SuperEntity::getId).collect(Collectors.toList());
        }
        if(CollectionUtils.isEmpty(serviceItemIds)){
            serviceItemIds.add(0L);
        }
    }
}
